package cn.pconline.autoclub.service;

import cn.pconline.autoclub.entity.Club;
import cn.pconline.autoclub.entity.ClubMember;
import cn.pconline.autoclub.entity.ClubStat;
import cn.pconline.autoclub.entity.ClubTotalMember;
import cn.pconline.autoclub.entity.MemberAll;
import cn.pconline.autoclub.entity.MemberStat;
import cn.pconline.autoclub.entity.MemberWeek;
import cn.pconline.autoclub.util.DateUtils;
import cn.pconline.autoclub.util.Pager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import org.gelivable.dao.GeliDao;
import org.gelivable.dao.GeliOrm;
import org.gelivable.dao.Mid;
import org.gelivable.dao.SqlBuilder;
import org.gelivable.dao.SqlPageBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.ResultSetExtractor;

/**
 * 排行榜
 *
 * @author chensy
 */
public class StatService {

    @Autowired
    private GeliOrm geliOrm;
    @Autowired
    private GeliDao geliDao;
    @Autowired
    private SqlPageBuilder pageBuilder;
    @Autowired
    private PagerService pagerService;
    @Autowired
    private UserService userService;
    @Autowired
    private ClubService clubService;

    /**
     * 车友会成员昨天24小时的贡献排行榜（数据由定时任务更新）
     *
     * @param clubId
     * @param num
     * @return
     */
    public List<MemberStat> getClubMemberDayPetrolTop(long clubId, int num) {
        //正常情况下，更新时间为今天，统计数据为昨天，但这里查询时不带上更新时间
        //因为一个人在一个车友会下只有一条统计数据
        SqlBuilder sql = new SqlBuilder();
        sql.appendSql("select * from ").appendSql(geliOrm.getTableName(MemberStat.class));
        sql.appendSql(" where club_id = ").appendValue(clubId);
        sql.appendSql(" and status = ").appendValue(MemberStat.STATUS_VALID);
        sql.appendSql(" and day_petrol > ").appendValue(0);
        sql.appendSql(" and DATE(day_petrol_update_at) = CURDATE() ");
        sql.appendSql(" order by day_petrol desc");
        try {
            List<MemberStat> list = geliDao.page(MemberStat.class, sql.getSql(), 1, num, sql.getValues());
            if (list != null) {
                for (MemberStat s : list) {
                    s.setUser(userService.findUser(s.getUserId()));
                }
                return list;
            }
        } catch (EmptyResultDataAccessException e) {
        }
        return Collections.emptyList();
    }

    /**
     * 车友会在上一个自然周里，按照其油值的增加量进行排行（数据由定时任务更新）
     *
     * @param num
     * @param seriesId
     * @param brandId
     * @param cityId
     * @param provinceId
     * @return
     */
    public List<ClubStat> getClubWeekPetrolTop(int num, long provinceId, long cityId, long brandId, long seriesId) {
        //正常情况下，更新时间为今天，统计数据为昨天，但这里查询时不带上更新时间
        //因为一个车友会只有一条统计数据
        SqlBuilder sql = new SqlBuilder();
        sql.appendSql("select a.* from ac_club_stat a ,ac_club b WHERE a.club_id = b.club_id");
        sql.appendSql(" and a.club_id = b.club_id and a.week_petrol > ").appendValue(0);
        if (provinceId > 0) {
            sql.appendSql(" and b.province_id = ").appendValue(provinceId);
        }
        if (cityId > 0) {
            sql.appendSql(" and b.city_id = ").appendValue(cityId);
        }
        if (brandId > 0) {
            sql.appendSql(" and b.brand_id = ").appendValue(brandId);
        }
        if (seriesId > 0) {
            sql.appendSql(" and b.series_id = ").appendValue(seriesId);
        }
        sql.appendSql(" order by a.week_petrol desc");
        try {
            List<ClubStat> list = geliDao.page(ClubStat.class, sql.getSql(), 1, num, sql.getValues());
            if (list != null) {
                for (ClubStat c : list) {
                    c.setClub(clubService.getClub(c.getClubId()));
                }
                return list;
            }
        } catch (EmptyResultDataAccessException e) {
        }
        return Collections.emptyList();
    }

    /**
     * @Description: 根据车友会id查找clubstat
     * @param:
     * @param clubId 车友会id
     * @return: ClubStat
     * @Date 2014-9-28 下午05:32:15
     */
    public ClubStat getClubStatByClubId(long clubId) {
        try {
            return geliDao.find(ClubStat.class, clubId);
        } catch (EmptyResultDataAccessException e) {
            return null;
        }
    }

    /**
     * 标记无效的统计记录
     *
     * @param userId
     * @param clubId
     */
    public void deleteMemberStat(long userId, long clubId) {
        SqlBuilder sql = new SqlBuilder();
        sql.appendSql("select * from ac_member_stat where club_id = ").appendValue(clubId);
        sql.appendSql(" and user_id = ").appendValue(userId);
        MemberStat s = geliDao.findFirst(MemberStat.class, sql.getSql(), sql.getValues());
        if (s != null) {
            s.setStatus(MemberStat.STATUS_INVALID);
            geliDao.update(s, "status");
        }
    }

    /**
     *
     * @param top 前几
     * @param orderType 1>周认证会员人数增加量;2>周会员人数增加量（全都是降序排序）
     * @return
     */
    public List<ClubTotalMember> listClubMemberNumWeekly(int top, int orderType) {
        SqlBuilder sql = new SqlBuilder();
        sql.appendSql("SELECT a.* FROM ac_club_total_member a,ac_club c where a.club_id = c.club_id and (c.status = ").appendValue(Club.STATUS_PASS).appendSql(" or c.status=").appendValue(Club.STATUS_LOCK).appendSql(" or c.status=").appendValue(Club.STATUS_SEALED).appendSql(")");

        if (orderType == 1) {
            sql.appendSql(" ORDER BY a.week_vip_total - a.lastweek_vip_total DESC");
        } else if (orderType == 2) {
            sql.appendSql(" ORDER BY a.week_total - a.lastweek_total DESC");
        }
        sql.appendSql(" limit ").appendValue(top);
        try {
            return geliDao.list(ClubTotalMember.class, sql.getSql(), sql.getValues());
        } catch (EmptyResultDataAccessException e) {
            return Collections.emptyList();
        }
    }

    /**
     * 车友会成员油值，主题，签到等操作的操作周排行榜方法
     *
     * @param clubId
     * @param userId
     * @param amount	加（减）分数量
     * @param item	类型（签到，油值。。等）
     * @return
     */
    public boolean updateWeekRank(long clubId, long userId, int amount, long item) {
        Date now = DateUtils.getNow();
        MemberWeek memberWeek = getMemberWeekByClubAndUser(clubId, userId);
        if (memberWeek == null) {
            memberWeek = MemberWeek.getInstance(clubId, userId, now);
            geliDao.create(memberWeek);
        } else {
            memberWeek.setUpdateAt(now);
        }
        switch ((int) item) {
            case PetrolService.ADD_PERSONAL_PETROL_ITEM_CHECKIN_1:
            case PetrolService.ADD_PERSONAL_PETROL_ITEM_CHECKIN_2:
            case PetrolService.ADD_PERSONAL_PETROL_ITEM_CHECKIN_3:
            case PetrolService.ADD_PERSONAL_PETROL_ITEM_CHECKIN_4:
            case PetrolService.ADD_PERSONAL_PETROL_ITEM_CHECKIN_5:
            case PetrolService.ADD_PERSONAL_PETROL_ITEM_CHECKIN_6:
            case PetrolService.ADD_PERSONAL_PETROL_ITEM_CHECKIN_7:
            case PetrolService.ADD_PERSONAL_PETROL_ITEM_CHECKIN_WAP_1:
            case PetrolService.ADD_PERSONAL_PETROL_ITEM_CHECKIN_WAP_2:
            case PetrolService.ADD_PERSONAL_PETROL_ITEM_CHECKIN_WAP_3:
            case PetrolService.ADD_PERSONAL_PETROL_ITEM_CHECKIN_WAP_4:
            case PetrolService.ADD_PERSONAL_PETROL_ITEM_CHECKIN_WAP_5:
            case PetrolService.ADD_PERSONAL_PETROL_ITEM_CHECKIN_WAP_6:
            case PetrolService.ADD_PERSONAL_PETROL_ITEM_CHECKIN_WAP_7:
                memberWeek.setCheckCount(memberWeek.getCheckCount() + 1);
                break;
            case PetrolService.ADD_PERSONAL_PETROL_ITEM_TOPIC:
                memberWeek.setTopicCount(memberWeek.getTopicCount() + 1);
                break;
            case PetrolService.ADD_PERSONAL_PETROL_ITEM_TOPIC_DELETE:
                memberWeek.setTopicCount(memberWeek.getTopicCount() - 1 > 0 ? memberWeek.getTopicCount() - 1 : 0);
                break;
            case PetrolService.ADD_PERSONAL_PETROL_ITEM_PICK:
                memberWeek.setPickCount(memberWeek.getPickCount() + 1);
                break;
            case PetrolService.ADD_PERSONAL_PETROL_ITEM_PICK_CANCEL:
                memberWeek.setPickCount(memberWeek.getPickCount() - 1 > 0 ? memberWeek.getPickCount() - 1 : 0);
                break;
            case PetrolService.ADD_PERSONAL_PETROL_ITEM_RECOMMEND:
                memberWeek.setRecommendCount(memberWeek.getRecommendCount() + 1);
                break;
            case PetrolService.ADD_PERSONAL_PETROL_ITEM_RECOMMEND_CANCEL:
                memberWeek.setRecommendCount(memberWeek.getRecommendCount() - 1 > 0 ? memberWeek.getRecommendCount() - 1 : 0);
                break;
            default:
                break;
        }
        memberWeek.setPetrol(memberWeek.getPetrol() + amount > 0 ? memberWeek.getPetrol() + amount : 0);
        int result = geliDao.update(memberWeek);
        return result > 0;
    }

    /**
     * 车友会成员油值，主题，签到等操作的操作总排行榜方法
     *
     * @param clubId
     * @param userId
     * @param amount	加（减）分数量
     * @param item	类型（签到，油值。。等）
     * @return
     */
    public boolean updateAllRank(long clubId, long userId, int amount, long item) {
        Date now = DateUtils.getNow();
        MemberAll memberAll = getMemberAllByClubAndUser(clubId, userId);
        if (memberAll == null) {
            memberAll = MemberAll.getInstance(clubId, userId, now);
            geliDao.create(memberAll);
        } else {
            memberAll.setUpdateAt(now);
        }
        switch ((int) item) {
            case PetrolService.ADD_PERSONAL_PETROL_ITEM_CHECKIN_1:
            case PetrolService.ADD_PERSONAL_PETROL_ITEM_CHECKIN_2:
            case PetrolService.ADD_PERSONAL_PETROL_ITEM_CHECKIN_3:
            case PetrolService.ADD_PERSONAL_PETROL_ITEM_CHECKIN_4:
            case PetrolService.ADD_PERSONAL_PETROL_ITEM_CHECKIN_5:
            case PetrolService.ADD_PERSONAL_PETROL_ITEM_CHECKIN_6:
            case PetrolService.ADD_PERSONAL_PETROL_ITEM_CHECKIN_7:
            case PetrolService.ADD_PERSONAL_PETROL_ITEM_CHECKIN_WAP_1:
            case PetrolService.ADD_PERSONAL_PETROL_ITEM_CHECKIN_WAP_2:
            case PetrolService.ADD_PERSONAL_PETROL_ITEM_CHECKIN_WAP_3:
            case PetrolService.ADD_PERSONAL_PETROL_ITEM_CHECKIN_WAP_4:
            case PetrolService.ADD_PERSONAL_PETROL_ITEM_CHECKIN_WAP_5:
            case PetrolService.ADD_PERSONAL_PETROL_ITEM_CHECKIN_WAP_6:
            case PetrolService.ADD_PERSONAL_PETROL_ITEM_CHECKIN_WAP_7:
                memberAll.setCheckCount(memberAll.getCheckCount() + 1);
                break;
            case PetrolService.ADD_PERSONAL_PETROL_ITEM_TOPIC:
                memberAll.setTopicCount(memberAll.getTopicCount() + 1);
                break;
            case PetrolService.ADD_PERSONAL_PETROL_ITEM_TOPIC_DELETE:
                memberAll.setTopicCount(memberAll.getTopicCount() - 1 > 0 ? memberAll.getTopicCount() - 1 : 0);
                break;
            case PetrolService.ADD_PERSONAL_PETROL_ITEM_PICK:
                memberAll.setPickCount(memberAll.getPickCount() + 1);
                break;
            case PetrolService.ADD_PERSONAL_PETROL_ITEM_PICK_CANCEL:
                memberAll.setPickCount(memberAll.getPickCount() - 1 > 0 ? memberAll.getPickCount() - 1 : 0);
                break;
            case PetrolService.ADD_PERSONAL_PETROL_ITEM_RECOMMEND:
                memberAll.setRecommendCount(memberAll.getRecommendCount() + 1);
                break;
            case PetrolService.ADD_PERSONAL_PETROL_ITEM_RECOMMEND_CANCEL:
                memberAll.setRecommendCount(memberAll.getRecommendCount() - 1 > 0 ? memberAll.getRecommendCount() - 1 : 0);
                break;
            default:
                break;
        }
        memberAll.setPetrol(memberAll.getPetrol() + amount > 0 ? memberAll.getPetrol() + amount : 0);
        int result = geliDao.update(memberAll);
        return result > 0;
    }

    /**
     *
     * 根据车友会id，用户id查找用户的周排行榜信息
     *
     * @param clubId
     * @param userId
     */
    public MemberWeek getMemberWeekByClubAndUser(long clubId, long userId) {
        SqlBuilder sql = new SqlBuilder();
        sql.appendSql(" select club_id,user_id from ").appendSql(geliOrm.getTableName(MemberWeek.class));
        sql.appendSql(" where club_id = ").appendValue(clubId);
        sql.appendSql(" and user_id = ").appendValue(userId);
        try {
            List<MemberWeek> list = geliDao.page(MemberWeek.class, sql.getSql(), 1, 1, sql.getValues());
            if (list != null && !list.isEmpty()) {
                return list.get(0);
            }
        } catch (EmptyResultDataAccessException e) {
        }
        return null;
    }

    /**
     *
     * 根据车友会id，用户id查找用户的总排行榜信息
     *
     * @param clubId
     * @param userId
     */
    public MemberAll getMemberAllByClubAndUser(long clubId, long userId) {
        SqlBuilder sql = new SqlBuilder();
        sql.appendSql(" select club_id, user_id from ").appendSql(geliOrm.getTableName(MemberAll.class));
        sql.appendSql(" where club_id = ").appendValue(clubId);
        sql.appendSql(" and user_id = ").appendValue(userId);
        try {
            List<MemberAll> list = geliDao.page(MemberAll.class, sql.getSql(), 1, 1, sql.getValues());
            if (list != null && !list.isEmpty()) {
                return list.get(0);
            }
        } catch (EmptyResultDataAccessException e) {
        }
        return null;
    }

    /**
     * 本周油值排行
     *
     * @param clubId
     * @param pageNo
     * @param pageSize
     * @return
     */
    public Pager<MemberWeek> pagerMemberWeek(long clubId, int pageNo, int pageSize) {
        return pagerMemberWeek(clubId, pageNo, pageSize, 0);
    }

    /**
     * 根据车友会id，分页查找周排行榜信息
     *
     * @param clubId
     * @param pageNo
     * @param pageSize
     * @param isYesterday (0:本周油值排行；1：昨天油值排行）
     *
     */
    @SuppressWarnings("unchecked")
    public Pager<MemberWeek> pagerMemberWeek(long clubId, int pageNo, int pageSize, int isYesterday) {
        if (clubId <= 0) {
            return null;
        }
        SqlBuilder sql = new SqlBuilder();
        sql.appendSql(" select info.club_id club_id,info.user_id user_id,mweek.club_id week_club_id,mweek.user_id week_user_id from ").appendSql(geliOrm.getTableName(ClubMember.class)).appendSql(" info");
        sql.appendSql(" left join ").appendSql(geliOrm.getTableName(MemberWeek.class)).appendSql(" mweek on  info.user_id = mweek.user_id ");
        sql.appendSql(" and info.club_id = mweek.club_id");
        sql.appendSql(" where info.club_id = ").appendValue(clubId);
        if (isYesterday == 0) {
            sql.appendSql(" order by mweek.petrol desc, mweek.rank,info.join_at");
        } else {
            sql.appendSql(" order by mweek.petrol_yesterday desc, mweek.petrol_yesterday, mweek.rank,info.join_at");
        }
        Pager<MemberWeek> pager = pagerService.pagerWithOutList(MemberWeek.class, sql, pageNo, pageSize);
        try {
            //左连接，按排行顺序，查出所有会员
            List<List<Object>> ids = geliDao.getJdbcTemplate().query(pageBuilder.buildPageSql(sql.getSql(), pageNo, pageSize), sql.getValues(), new ResultSetExtractor<List<List<Object>>>() {
                @Override
                public List<List<Object>> extractData(ResultSet rs) throws SQLException {
                    List<List<Object>> list = new ArrayList<List<Object>>();
                    while (rs.next()) {
                        long clubId = rs.getLong("club_id");
                        long userId = rs.getLong("user_id");
                        Object weekClubId = rs.getObject("week_club_id");
                        Object weekUserId = rs.getObject("week_user_id");
                        List<Object> li = new ArrayList<Object>();
                        li.add(clubId);
                        li.add(userId);
                        li.add(weekClubId);
                        li.add(weekUserId);
                        list.add(li);
                    }
                    return list;
                }
            });
            //对于没有排行记录的会员初始化一个实体
            List<MemberWeek> list = new ArrayList<MemberWeek>();
            for (List<Object> li : ids) {
                MemberWeek m = null;
                long cid = (Long) li.get(0), uid = (Long) li.get(1);
                if (li.get(2) != null && li.get(3) != null) {
                    m = getMemberWeekByClubAndUser(cid, uid);
                    m.setRankUpDown(m.getRankYesterday() - m.getRankYesterdayBefore());
                }
                if (m == null) {
                    m = MemberWeek.getInstance(cid, uid, new Date());
                }
                list.add(m);
            }
            pager.setResultList(userService.loadTransientUsers(list));
        } catch (EmptyResultDataAccessException e) {
            pager.setResultList(new ArrayList<MemberWeek>());
        }
        return pager;
    }

    /**
     * 根据车友会id，分页查找总排行榜信息
     *
     * @param clubId
     * @param pageNo
     * @param pageSize
     */
    @SuppressWarnings("unchecked")
    public Pager<MemberAll> pagerMemberAll(long clubId, int pageNo, int pageSize) {
        if (clubId <= 0) {
            return null;
        }
        SqlBuilder sql = new SqlBuilder();
        sql.appendSql(" select info.club_id club_id,info.user_id user_id,mall.club_id mall_club_id,mall.user_id mall_user_id from ").appendSql(geliOrm.getTableName(ClubMember.class)).appendSql(" info");
        sql.appendSql(" left join ").appendSql(geliOrm.getTableName(MemberAll.class)).appendSql(" mall on  info.user_id = mall.user_id ");
        sql.appendSql(" and info.club_id = mall.club_id");
        sql.appendSql(" where info.club_id = ").appendValue(clubId);
        sql.appendSql(" order by mall.petrol desc, mall.update_at,info.join_at");
        Pager<MemberAll> pager = pagerService.pagerWithOutList(MemberAll.class, sql, pageNo, pageSize);
        try {
            //左连接，按排行顺序，查出所有会员
            List<List<Object>> ids = geliDao.getJdbcTemplate().query(pageBuilder.buildPageSql(sql.getSql(), pageNo, pageSize), sql.getValues(), new ResultSetExtractor<List<List<Object>>>() {
                @Override
                public List<List<Object>> extractData(ResultSet rs) throws SQLException {
                    List<List<Object>> list = new ArrayList<List<Object>>();
                    while (rs.next()) {
                        long clubId = rs.getLong("club_id");
                        long userId = rs.getLong("user_id");
                        Object allClubId = rs.getObject("mall_club_id");
                        Object allUserId = rs.getObject("mall_user_id");
                        List<Object> li = new ArrayList<Object>();
                        li.add(clubId);
                        li.add(userId);
                        li.add(allClubId);
                        li.add(allUserId);
                        list.add(li);
                    }
                    return list;
                }
            });
            //对于没有排行记录的会员初始化一个实体
            List<MemberAll> list = new ArrayList<MemberAll>(ids.size());
            for (List<Object> li : ids) {
                MemberAll m = null;
                long cid = (Long) li.get(0), uid = (Long) li.get(1);
                if (li.get(2) != null && li.get(3) != null) {
                    m = getMemberAllByClubAndUser(cid, uid);
                }
                if (m == null) {
                    m = MemberAll.getInstance(cid, uid, new Date());
                }
                list.add(m);
            }
            pager.setResultList(userService.loadTransientUsers(list));
        } catch (EmptyResultDataAccessException e) {
            pager.setResultList(new ArrayList<MemberAll>());
        }
        return pager;
    }

    /**
     * 获取用户所在车友会的周排行榜 再算出名次
     *
     * @param clubId
     * @param userId
     */
    public int getWeekRank(long clubId, long userId) {
        if (clubId <= 0 || userId <= 0) {
            return -1;
        }
        SqlBuilder sql = new SqlBuilder();
        sql.appendSql(" select mweek.user_id user_id from ").appendSql(geliOrm.getTableName(ClubMember.class)).appendSql(" info");
        sql.appendSql(" left join ").appendSql(geliOrm.getTableName(MemberWeek.class)).appendSql(" mweek on  info.user_id = mweek.user_id ");
        sql.appendSql(" and info.club_id = mweek.club_id");
        sql.appendSql(" where mweek.club_id = ").appendValue(clubId);
        sql.appendSql(" order by mweek.petrol desc, mweek.rank,info.join_at");
        try {
            List<Long> idsList = geliDao.getJdbcTemplate().query(sql.getSql(), GeliDao.longIdRowMapper, sql.getValues());
            if (idsList != null) {
                for (int i = 0; i < idsList.size(); i++) {
                    if (idsList.get(i) == userId) {
                        return i + 1;
                    }
                }
            } else {
                return -1;
            }
        } catch (EmptyResultDataAccessException e) {
            return -1;
        }
        return -1;
    }

    /**
     * 获取用户所在车友会的总排榜 再算出名次
     *
     * @param clubId
     * @param userId
     */
    public int getAllRank(long clubId, long userId) {
        if (clubId <= 0 || userId <= 0) {
            return -1;
        }
        SqlBuilder sql = new SqlBuilder();
        sql.appendSql(" select mall.user_id user_id from ").appendSql(geliOrm.getTableName(ClubMember.class)).appendSql(" info");
        sql.appendSql(" left join ").appendSql(geliOrm.getTableName(MemberAll.class)).appendSql(" mall on  info.user_id = mall.user_id ");
        sql.appendSql(" and mall.club_id = info.club_id ");
        sql.appendSql(" where mall.club_id = ").appendValue(clubId);
        sql.appendSql(" order by mall.petrol desc, mall.update_at,info.join_at");
        try {
            List<Long> idsList = geliDao.getJdbcTemplate().query(sql.getSql(), GeliDao.longIdRowMapper, sql.getValues());
            if (idsList != null) {
                for (int i = 0; i < idsList.size(); i++) {
                    if (idsList.get(i) == userId) {
                        return i + 1;
                    }
                }
            } else {
                return -1;
            }

        } catch (EmptyResultDataAccessException e) {
            return -1;
        }
        return -1;
    }

    /**
     * 用户加入车友会时，创建周排行榜信息
     *
     * @param clubId
     * @param userId
     */
    public MemberWeek createMemberWeek(long userId, long clubId) {
        Date now = DateUtils.getNow();
        MemberWeek memberWeek = getMemberWeekByClubAndUser(clubId, userId);
        if (memberWeek == null) {
            memberWeek = MemberWeek.getInstance(clubId, userId, now);
            geliDao.create(memberWeek);
        } else {
            memberWeek = MemberWeek.getInstance(clubId, userId, now);
            geliDao.update(memberWeek);
        }
        return memberWeek;
    }

    /**
     * 用户加入车友会时，创建总排行榜信息
     *
     * @param clubId
     * @param userId
     */
    public MemberAll createMemberAll(long userId, long clubId) {
        Date now = DateUtils.getNow();
        MemberAll memberAll = getMemberAllByClubAndUser(clubId, userId);
        if (memberAll == null) {
            memberAll = MemberAll.getInstance(clubId, userId, now);
            geliDao.create(memberAll);
        } else {//如果之前已经有记录的，就全部字段都重新update（不过现在基本不会有这种数据）
            memberAll = MemberAll.getInstance(clubId, userId, now);
            geliDao.update(memberAll);
        }
        return memberAll;
    }

    /**
     * 删除会员总排行记录（退出车友会时需要删除）
     *
     * @param userId
     * @param clubId
     * @return
     */
    public int deleteMemberAll(long userId, long clubId) {
        MemberAll m = getMemberAllByClubAndUser(clubId, userId);
        if (m != null) {
            return geliDao.delete(m, new Mid(m.getClubId(), m.getUserId()));
        }
        return 0;
    }

    /**
     * 删除会员周排行记录（退出车友会时需要删除）
     *
     * @param userId
     * @param clubId
     * @return
     */
    public int deleteMemberWeek(long userId, long clubId) {
        MemberWeek m = getMemberWeekByClubAndUser(clubId, userId);
        if (m != null) {
            return geliDao.delete(m, new Mid(m.getClubId(), m.getUserId()));
        }
        return 0;
    }

    /**
     * 按活跃度列出前num的车友会
     *
     * @param num
     * @param seriesId
     * @param brandId
     * @param cityId
     * @param provinceId
     * @return
     */
    public List<ClubStat> listClubByRankPetrol(int num) {
        SqlBuilder sql = new SqlBuilder();
        sql.appendSql(" select ac_club_stat.* from ac_club left join ac_club_stat on ac_club.club_id = ac_club_stat.club_id where 1=1 ");
        sql.appendSql(" order by ac_club_stat.rank_petrol desc, ac_club.total_petrol desc, ac_club.create_at  ");
        try {
            List<ClubStat> list = geliDao.page(ClubStat.class, sql.getSql(), 1, num);
            if (list != null) {
                for (ClubStat c : list) {
                    c.setClub(clubService.getClub(c.getClubId()));
                }
                return list;
            }
        } catch (EmptyResultDataAccessException e) {
        }
        return Collections.emptyList();
    }
}
